有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何解决Android MultiDex应用程序实例空指针异常?

我想在我的Android项目中进行核心api服务集成。 我的核心服务课程如下:

public class TestApplication extends MultiDexApplication {
    private static final String LOG_TAG_NETWORK = "GNetwork";
    public static JacksonConverterFactory factory;
    private static TestApplication instance;
    private OkHttpClient.Builder okHttpBuilder;
    private TestService testtService;
    private Location lastKnownLocation;

public static TestApplication getInstance() {
    return instance;
}

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    Pref.init(this);

    okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.connectTimeout(UrlConstants.CONNECT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .readTimeout(UrlConstants.READ_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .writeTimeout(UrlConstants.WRITE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    if (BuildConfig.LOG_ENABLED) {
        HttpLoggingInterceptor httpLoggingInterceptor =
                new HttpLoggingInterceptor(message -> Log.d(LOG_TAG_NETWORK, message));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpBuilder.addInterceptor(httpLoggingInterceptor);
    }
    factory = getJacksonConverterFactory();
}

@NonNull
private JacksonConverterFactory getJacksonConverterFactory() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return JacksonConverterFactory.create(objectMapper);
}

public void setupRetrofit() {

    String BASE_URL = "http://xxxxx";

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpBuilder.build())
            .addConverterFactory(factory).build();

    testService = retrofit.create(TestService.class);
}

public TestService getTestService() {
    return testService;
    }
}

然后我从这个核心类创建了一个实例。但在这里,我的常量getIntance值返回null

TestApplication.getInstance().setupRetrofit();

我不明白GetInstance方法总是返回null

在我的应用程序中build.gradle文件是multiDexEnabled true

如何解决这种情况


共 (1) 个答案

  1. # 1 楼答案

    不要像这样使用应用程序实例。对于get应用程序实例,您需要活动,并且在活动中可以使用

        static TestApplication getInstance(Activity activity) {
            if (instance == null)
                instance = ((TestApplication) activity.getApplication());
            return instance;
        }
    

    这将解决您的问题,但您实施改造和使用它的方式并不是最佳做法。你可以找到不需要运动的更好方法